package com.boat.framework.base.api;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * 分页参数
 * 
 * @author 周江
 *
 */
@Setter
@Getter
public class PageParam implements Serializable {
	private static final long serialVersionUID = -3695232609191513090L;

	public static final int DEFAULT_PAGE_NUM = 1;

	public static final int DEFAULT_PAGE_SIZE = 10;

	/** 默认最大返回记录数 */
	public static final int MAX_PAGE_SIZE = 1000;

	/**
	 * 页码，从1开始
	 */
	private int pageNum;
	/**
	 * 每页记录数
	 */
	private int pageSize;

	public PageParam() {
		super();
		this.pageNum = DEFAULT_PAGE_NUM;
		this.pageSize = DEFAULT_PAGE_SIZE;
	}

	public PageParam(int pageNum, int pageSize) {
		super();
		this.pageNum = pageNum;
		this.pageSize = pageSize;
	}

	// -----------链式方法
	public static PageParam create() {
		return new PageParam();
	}

	public PageParam pageNum(int pageNum) {
		this.setPageNum(pageNum);
		return this;
	}

	public PageParam pageSize(int pageSize) {
		this.setPageSize(pageSize);
		return this;
	}

	/**
	 * 增加排序字段，字段名驼峰格式（如userName）
	 * 
	 * @param field 字段名，格式支持userName或user_name，建议userName
	 * @param sort 大小写不敏感,asc,desc
	 * @return
	 */
	public PageParam addOrder(String field, String sort) {
		orders.add(new Order(field, sort));
		return this;
	}

	// -------------------排序字段
	private List<Order> orders = new ArrayList<>();

	@Getter
	@Setter
	@AllArgsConstructor
	public class Order {
		private static final String UNDERLINE = "_";

		/**
		 * 排序字段
		 */
		private String field;

		/**
		 * 排序顺序，大小写不敏感：asc,desc
		 */
		private String sort;

		/**
		 * 返回数据表字段名，如userName,返回user_name
		 * @return
		 */
		public String getTableColumn() {
			return camelToUnderline(field);
		}
		
		/**
		 * 驼峰转下划线，如userName,返回user_name
		 * 
		 * @param param 内容
		 * @return 返回转换后的字符串
		 */
		private String camelToUnderline(String param) {
			if (param == null || "".equals(param.trim())) {
				return "";
			}
			int len = param.length();
			StringBuilder sb = new StringBuilder(len);
			for (int i = 0; i < len; i++) {
				char c = param.charAt(i);
				int preIndex = i - 1;
				int nextIndex = i + 1;
				// 是否需要变为小写字母
				boolean needToLower = (Character.isUpperCase(c) && preIndex > 0
						&& Character.isLowerCase(param.charAt(preIndex)))
						|| (Character.isUpperCase(c) && nextIndex < len
								&& Character.isLowerCase(param.charAt(nextIndex)));

				if (needToLower) {
					if (i > 0) {
						sb.append(UNDERLINE);
					}
					sb.append(Character.toLowerCase(c));
				} else {
					sb.append(c);
				}
			}
			return sb.toString();
		}
	}

}
